<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    name:<input type="text" name="username"></br>
    password:<input type="password" name="password"></br>
    <button onclick="register()">注册</button>
    <button onclick="login()">登录</button>
    <button onclick="relogin()">再登录</button>
</body>
<script>
    let token='';
    function register(){
        let username=document.getElementsByName('username')[0].value
        let password=document.getElementsByName('password')[0].value
        ajax_register(username,password)
    }
    function login(){
        let username=document.getElementsByName('username')[0].value
        let password=document.getElementsByName('password')[0].value
        ajax_login(username,password)
    }
    function relogin(){
        ajax_relogin()
    }
    function ajax_register(username,password){
        let xhr=new XMLHttpRequest()
        xhr.open('POST','http://127.0.0.1:3007/api/reguser')
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(`username=${username}&password=${password}`)
        xhr.onreadystatechange=function(){
            if(xhr.readyState===4 && xhr.status>=200 && xhr.status<300){
                document.getElementsByTagName('button')[0].innerHTML=xhr.responseText
            }
        }
    }
    function ajax_login(username,password){
        let xhr=new XMLHttpRequest()
        xhr.open('POST','http://127.0.0.1:3007/api/login')
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(`username=${username}&password=${password}`)
        xhr.onreadystatechange=function(){
            if(xhr.readyState===4 && xhr.status>=200 && xhr.status<300){
                token=JSON.parse(xhr.responseText).token
            }
        }
    }
    function ajax_relogin(){
        let xhr=new XMLHttpRequest()
        xhr.open('GET','http://127.0.0.1:3007/user')
        xhr.setRequestHeader("Authorization", token);
        xhr.send()
        xhr.onreadystatechange=function(){
            if(xhr.readyState===4 && xhr.status>=200 && xhr.status<300){
                console.log(xhr.responseText)
            }
        }
    }
    
    
</script>
</html>